<?php

namespace app\service;

use app\model\admin\SysMenu;
use app\model\admin\SysRole;
use app\model\admin\SysRoleMenu;
use app\model\admin\SysUser;
use app\model\admin\SysUserRole;
use think\facade\Db;

class SysUserService
{
    public static $admin_id = 100;
    public static function getInfo($user_id)
    {
        
        $is_admin = false;
        if( $user_id == self::$admin_id ){
            $is_admin = true;
        }

        $user = SysUser::where('id', $user_id)->find();

       
        if($user == null){
            return error('用户不存在');
        }
        // 获取用户角色id，获取角色菜单
        $user_role_id = SysUserRole::where('user_id', $user_id)->column('role_id');
        if($is_admin == false && empty($user_role_id)){
            return error('未分配权限');
        }
        $user_role = SysRole::whereIn('id', $user_role_id)->column('role_key');

        if($is_admin){
            $permissions = ['*:*:*'];
            $user_role = ['admin'];
        }else{
            $user_role_menu_id = SysRoleMenu::whereIn('role_id', $user_role_id)->column('menu_id');
            $permissions = SysMenu::where('menu_type', 'F')->whereIn('id', $user_role_menu_id)->column('perms');
        }

        return success([
            'permissions' => $permissions,
            'roles' => $user_role,
            'user' => $user,
        ]);
    }

    public static function getRouters($user_id){
        $is_admin = false;
        if( $user_id == self::$admin_id ){
            $is_admin = true;
        }
        if($is_admin == true){
            $menus = SysMenu::whereIn('menu_type', ['M','C'])->order('order_num','asc')->select();
        }else{
            $user = SysUser::where('id', $user_id)->find();
            $roles = $user->roles;

            $roles_id = Db::table('sys_user_role')->where('user_id', $user_id)->column('role_id');
            //获取角色菜单
            $role_menus_id = SysRoleMenu::whereIn('role_id',$roles_id)->column('menu_id');
            if($role_menus_id){
                $role_menus_id = array_unique($role_menus_id);
            }
            //获取菜单
            $menus = SysMenu::whereIn('id',$role_menus_id)->whereIn('menu_type', ['M','C'])->order('order_num','asc')->select();
        }

        $menus_tree = makeTree($menus->toArray(),'id', 'parent_id');

        $menus_routes = generateRouters($menus_tree);
        return $menus_routes;
    }



}
